package com.gameley.dmgtpf.root.controller;

import com.gameley.dmgtpf.common.core.aspect.MyDoneTime;
import com.gameley.dmgtpf.common.utils.PubEnvUtil;
import com.gameley.dmgtpf.common.utils.TokenUtil;
import com.gameley.dmgtpf.root.service.AdminsService;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;

@RestController
public class UserLoginController
{
    
    // 因为使用了@RestController注解，
    // 而@RestController = @Controller + @ResponseBody
    // 其中@ResponseBody注解的作用是，
    // 将方法的返回值，以特定的格式写入到response的body区域，进而将数据返回给客户端。所以只返回字符串。
    @Autowired
    private AdminsService adminsService;
    

    // @ResponseBody
    @MyDoneTime(param = "UserLoginController.login")
    @RequestMapping("/login")
    public String userLogin(HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session)
            throws NoSuchAlgorithmException
    {
        // int i=0/0;
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        String josnStr = request.getParameter("josnStr");
        JsonElement jsonTree = new Gson().toJsonTree(josnStr);
        if (adminsService.userLogin(name, pass))
        {
            session.setAttribute("loginUser", name);
            String str = name + "_and_" + pass;
            
            // 获取token
            String token = TokenUtil.getToken(str);
            session.setAttribute("token", token);
            
            return PubEnvUtil.getSuccessMsg(token);
            // return "redirect:/main.html";
        }
        else
        {
            model.addAttribute("msg", "用户名或密码错误!");
            // return "index.html";
            return PubEnvUtil.getErrorMsg("用户名或密码错误!");
        }
        
    }
    
    @MyDoneTime(param = "UserLoginController.logout")
    @RequestMapping("/logout")
    public String userLogout(HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session)
    {
        session.setAttribute("loginUser", null);
        
        return PubEnvUtil.getSuccessMsg("logout succeeded ! ");
    }

}
